/*
 * 人人信用管理有限公司版权所有.
 * 
 * @Description:
 * 
 * @author: liyuliang
 * 
 * @date: 20 Apr 2017 10:44:16 am
 * 
 * 注意：本内容仅限于人人信用管理有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */

package com.rrx360.common.dao;

import java.util.ArrayList;
import java.util.List;

public class SqlQueryEntry extends QueryEntry {

  private List<Object> entityList;

  public SqlQueryEntry(CommonDao commonDao) {
    this.commonDao = commonDao;
  }

  public SqlQueryEntry(String ql) {
    super(ql, null, null, null);
  }

  public SqlQueryEntry(String ql, String countQl) {
    super(ql, countQl, null, null);
  }

  public SqlQueryEntry(String ql, Long start, Integer fetchSize) {
    super(ql, null, start, fetchSize);
  }

  public SqlQueryEntry(String ql, String countQl, Long start, Integer fetchSize) {
    super(ql, countQl, start, fetchSize);
  }

  public SqlQueryEntry addEntity(Class<?> entityClass) {
    if (entityList == null) {
      entityList = new ArrayList<Object>();
    }
    entityList.add(entityClass);
    return this;
  }

  public SqlQueryEntry addEntity(String name, Class<?> entityClass) {
    if (entityList == null) {
      entityList = new ArrayList<Object>();
    }
    entityList.add(new Object[] {name, entityClass});
    return this;
  }

  public SqlQueryEntry addEntitys(Class<?>[] entityClasses) {
    for (Class<?> clazz : entityClasses) {
      addEntity(clazz);
    }
    return this;
  }


  @Override
  public List exec(long start, int fetchSize) {
    return getCommonDao().selectByNativeSql(ql.toString(), params, entityList, start, fetchSize);
  }

  @Override
  public List exec() {
    if (start != null && fetchSize != null) {
      return exec(start, fetchSize);
    }
    return getCommonDao().selectByNativeSql(ql.toString(), params, entityList);
  }

  @Override
  public long execCount() {
    if (countQl == null) {
      convertQlToCountQl();
    }
    return getCommonDao().countByNativeSql(countQl.toString(), params);
  }

  @Override
  public long execUpdate() {
    return getCommonDao().updateByNativeSql(ql.toString(), params);
  }
}
